<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>用户与学校管理系统</title>
    <style>
      :root {
        --primary-color: #007bff;
        --success-color: #28a745;
        --danger-color: #dc3545;
        --background-color: #f8f9fa;
        --text-color: #333;
      }

      body {
        font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
        max-width: 1200px;
        margin: 2rem auto;
        padding: 0 20px;
        background-color: var(--background-color);
        color: var(--text-color);
      }

      .container {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 2rem;
      }

      .section {
        background: white;
        padding: 2rem;
        border-radius: 12px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      }

      .form-group {
        margin-bottom: 1.5rem;
      }

      label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 500;
      }

      input,
      select {
        width: 100%;
        padding: 0.8rem;
        border: 2px solid #ddd;
        border-radius: 6px;
        font-size: 1rem;
        transition: border-color 0.3s;
      }

      input:focus,
      select:focus {
        border-color: var(--primary-color);
        outline: none;
      }

      button {
        padding: 0.8rem 1.5rem;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        transition: opacity 0.3s;
        font-weight: 500;
      }

      button.primary {
        background-color: var(--primary-color);
        color: white;
      }

      button.success {
        background-color: var(--success-color);
        color: white;
      }

      button.danger {
        background-color: var(--danger-color);
        color: white;
      }

      button:hover {
        opacity: 0.9;
      }

      .result {
        margin-top: 1rem;
        padding: 1rem;
        border-radius: 6px;
        display: none;
        animation: fadeIn 0.3s;
      }

      .success {
        background-color: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
      }

      .error {
        background-color: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
      }

      ul {
        list-style-type: none;
        padding: 0;
      }

      li {
        background: #fff;
        padding: 1rem;
        margin-bottom: 0.5rem;
        border-radius: 6px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
      }

      @media (max-width: 768px) {
        .container {
          grid-template-columns: 1fr;
        }
      }

      @keyframes fadeIn {
        from {
          opacity: 0;
          transform: translateY(-10px);
        }
        to {
          opacity: 1;
          transform: translateY(0);
        }
      }
    </style>
  </head>
  <body>
    <h1 class="text-center">用户与学校管理系统</h1>
    <div class="container">
      <div class="section">
        <h2>创建用户</h2>
        <form id="userForm">
          <div class="form-group">
            <label for="name">姓名:</label>
            <input type="text" id="name" required />
          </div>
          <div class="form-group">
            <label for="email">邮箱:</label>
            <input type="email" id="email" required />
          </div>
          <div class="form-group">
            <label for="school">学校:</label>
            <select id="school"></select>
          </div>
          <button type="submit" class="primary">创建用户</button>
        </form>
        <button id="fetchUsers" class="primary">查询所有用户</button>
        <div id="usersList"></div>
      </div>

      <div class="section">
        <h2>管理学校</h2>
        <form id="schoolForm">
          <div class="form-group">
            <label for="schoolName">学校名称:</label>
            <input type="text" id="schoolName" required />
          </div>
          <input type="hidden" id="schoolId" />
          <button type="submit" class="success">新增学校</button>
        </form>
        <button id="fetchSchoolDetails" class="primary">获取学校详情</button>
        <div id="schoolDetails"></div>
        <div id="schoolsList"></div>
      </div>
    </div>
    <div id="result" class="result"></div>

    <script>
      const config = {
        apiUrl: "http://localhost:4000/graphql",
        successDuration: 5000,
        errorDuration: 8000,
      };

      const elements = {
        userForm: document.getElementById("userForm"),
        schoolForm: document.getElementById("schoolForm"),
        schoolSelect: document.getElementById("school"),
        usersList: document.getElementById("usersList"),
        schoolsList: document.getElementById("schoolsList"),
        resultDiv: document.getElementById("result"),
        fetchUsersButton: document.getElementById("fetchUsers"),
      };

      // 初始化加载学校列表
      fetchSchools();
      document
        .getElementById("fetchSchoolDetails")
        .addEventListener("click", fetchSchoolDetails);

      // 学校相关操作
      async function fetchSchools() {
        try {
          const response = await graphqlRequest({
            query: `
              query {
                schools {
                  id
                  name
                }
              }
            `,
          });

          if (response.errors) throw new Error(response.errors[0].message);

          displaySchools(response.data.schools);
          populateSchoolSelect(response.data.schools);
        } catch (error) {
          showResult("error", error.message);
        }
      }

      function populateSchoolSelect(schools) {
        elements.schoolSelect.innerHTML =
          '<option value="">无学校</option>' +
          schools
            .map(
              (school) => `<option value="${school.id}">${school.name}</option>`
            )
            .join("");
      }

      function displaySchools(schools) {
        elements.schoolsList.innerHTML = `
          <h3>所有学校</h3>
          <ul>
            ${schools
              .map(
                (school) => `
              <li>
                <div class="school-info">
                  <strong>${school.name}</strong> (ID: ${school.id})
                </div>
                <div class="school-actions">
                  <button class="primary" onclick="editSchool('${
                    school.id
                  }', '${escapeQuotes(school.name)}')">编辑</button>
                  <button class="danger" onclick="deleteSchool('${
                    school.id
                  }')">删除</button>
                </div>
              </li>
            `
              )
              .join("")}
          </ul>
        `;
      }

      function editSchool(id, name) {
        document.getElementById("schoolId").value = id;
        document.getElementById("schoolName").value = name;
        elements.schoolForm.querySelector('button[type="submit"]').textContent =
          "更新学校";
      }

      async function deleteSchool(id) {
        if (!confirm("确定要删除这所学校吗？")) return;

        try {
          const response = await graphqlRequest({
            query: `
              mutation DeleteSchool($id: String!) {
                deleteSchool(id: $id) {
                  id
                  name
                }
              }
            `,
            variables: { id },
          });

          if (response.errors) throw new Error(response.errors[0].message);

          showResult(
            "success",
            `学校 ${response.data.deleteSchool.name} 删除成功！`
          );
          fetchSchools();
        } catch (error) {
          showResult("error", error.message);
        }
      }

      // 用户相关操作
      async function fetchUsers() {
        try {
          const response = await graphqlRequest({
            query: `
              query {
                users {
                  id
                  name
                  email
                  school {
                    id
                    name
                  }
                }
              }
            `,
          });

          if (response.errors) throw new Error(response.errors[0].message);

          displayUsers(response.data.users);
        } catch (error) {
          showResult("error", error.message);
        }
      }

      function displayUsers(users) {
        elements.usersList.innerHTML = `
          <h3>所有用户</h3>
          <ul>
            ${users
              .map(
                (user) => `
              <li>
                <strong>姓名:</strong> ${user.name}<br>
                <strong>邮箱:</strong> ${user.email}<br>
                <strong>学校:</strong> ${user.school?.name || "无"}
              </li>
            `
              )
              .join("")}
          </ul>
        `;
      }

      // 表单提交处理
      elements.userForm.addEventListener("submit", async (e) => {
        e.preventDefault();

        try {
          const response = await graphqlRequest({
            query: `
              mutation CreateUser($name: String!, $email: String!, $schoolId: ID) {
                createUser(name: $name, email: $email, schoolId: $schoolId) {
                  id
                  name
                  email
                  school {
                    id
                    name
                  }
                }
              }
            `,
            variables: {
              name: document.getElementById("name").value,
              email: document.getElementById("email").value,
              schoolId: elements.schoolSelect.value || null,
            },
          });

          if (response.errors) throw new Error(response.errors[0].message);

          showResult(
            "success",
            `用户 ${response.data.createUser.name} 创建成功！ID: ${response.data.createUser.id}`
          );
          elements.userForm.reset();
        } catch (error) {
          showResult("error", error.message);
        }
      });

      elements.schoolForm.addEventListener("submit", async (e) => {
        e.preventDefault();

        const name = document.getElementById("schoolName").value;
        const id = document.getElementById("schoolId").value;
        const isUpdate = !!id;

        try {
          const response = await graphqlRequest({
            query: isUpdate
              ? `
              mutation UpdateSchool($id: String!, $name: String!) {
                updateSchool(id: $id, name: $name) {
                  id
                  name
                }
              }
            `
              : `
              mutation CreateSchool($name: String!) {
                createSchool(name: $name) {
                  id
                  name
                }
              }
            `,
            variables: { id, name },
          });

          if (response.errors) throw new Error(response.errors[0].message);

          const action = isUpdate ? "更新" : "创建";
          const school =
            response.data[isUpdate ? "updateSchool" : "createSchool"];
          showResult("success", `学校 ${school.name} ${action}成功！`);

          elements.schoolForm.reset();
          document.getElementById("schoolId").value = "";
          elements.schoolForm.querySelector(
            'button[type="submit"]'
          ).textContent = "新增学校";
          fetchSchools();
        } catch (error) {
          showResult("error", error.message);
        }
      });

      elements.fetchUsersButton.addEventListener("click", fetchUsers);

      // 通用函数
      async function graphqlRequest({ query, variables }) {
        const response = await fetch(config.apiUrl, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ query, variables }),
        });
        return response.json();
      }

      function showResult(type, message) {
        elements.resultDiv.className = `result ${type}`;
        elements.resultDiv.textContent = message;
        elements.resultDiv.style.display = "block";

        setTimeout(
          () => {
            elements.resultDiv.style.display = "none";
          },
          type === "success" ? config.successDuration : config.errorDuration
        );
      }

      function escapeQuotes(str) {
        return str.replace(/'/g, "\\'");
      }

      async function fetchSchoolDetails() {
        try {
          const schoolId = prompt("请输入要查询的学校 ID:");
          if (!schoolId) return;

          const response = await graphqlRequest({
            query: `
        query GetSchoolDetails($id: ID!) {
          school(id: $id) {
            id
            name
            users {
              id
              name
              email
            }
          }
        }
      `,
            variables: { id: schoolId },
          });

          if (response.errors) throw new Error(response.errors[0].message);
          const school = response.data.school;
          if (!school) {
            showResult("error", "未找到该学校");
            return;
          }
          displaySchoolDetails(school);
        } catch (error) {
          showResult("error", error.message);
        }
      }

      function displaySchoolDetails(school) {
        const schoolDetailsDiv = document.getElementById("schoolDetails");
        schoolDetailsDiv.innerHTML = `
    <h3>学校详情 - ${school.name}</h3>
    <p><strong>学校 ID:</strong> ${school.id}</p>
    <h4>关联用户</h4>
    <ul>
      ${
        school.users.length > 0
          ? school.users
              .map(
                (user) => `
          <li>
            <strong>姓名:</strong> ${user.name}<br>
            <strong>邮箱:</strong> ${user.email}<br>
            <strong>用户 ID:</strong> ${user.id}
          </li>
        `
              )
              .join("")
          : "<li>暂无关联用户</li>"
      }
    </ul>
  `;
      }
    </script>
  </body>
</html>
